const con = require("./mysql");
const bodyParser = require("body-parser");
const express = require("express");
const app = express();
const port = 9000;

// 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 跨域请求允许
app.all('*',function (req,res,next) {
  res.header('Access-Control-Allow-Origin','*')
  res.header('Access-Control-Allow-Headers','X-Requested-With,Content-Type')
  res.header('Access-Control-Allow-Methods','GET,POST,OPTIONS')
  next()
})

// 查询座位信息
app.get("/seat-info", (req, res) => {
  const command = 'SELECT * FROM seat';
  con.getConnection((err, connection) => {
    if (err) throw err;
    connection.query(command, (err, sRes) => {
      if (err) {
        res.send("query error");
      } else {
        res.send({ res: sRes });
      }
      connection.destroy()
    });
  });
});

// 更新座位信息
app.post('/update-seat', (req, res) => {
  const { body:seats } = req
  let command = ''
  seats?.seat?.forEach(ele => {
    command += `update seat set sold = 1 where s_id=${ele};`
  });

  con.getConnection((err, connection) => {
    if (err) throw err;
    connection.query(command, (err, sRes) => {
      if (err) {
        res.send("query error");
        console.log(err)
      } else {
        res.send({ res: sRes });
      }
      connection.destroy()
    });
  });
})

// 启动、监听
app.listen(port, () => console.log("服务启动，监听端口:" + port));
